<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
<!--   禁用id搜索   -->
<!--      <el-form-item label="套餐id" prop="packId">
        <el-input
          v-model="queryParams.packId"
          placeholder="请输入套餐id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="管理员id" prop="adminId">
        <el-input
          v-model="queryParams.adminId"
          placeholder="请输入管理员id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>-->
      <el-form-item label="套餐名称" prop="packName">
        <el-input
          v-model="queryParams.packName"
          placeholder="请输入套餐名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="套餐价格" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入套餐价格"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上架时间" prop="shopTime" style="width: 250px;">
        <el-select
            v-model="queryParams.shopTime"
            placeholder="请选择上架时间"
            clearable
            @change="handleQuery"
        >
        <el-option
            v-for="item in shopTimeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
        </el-select>
      </el-form-item>
      <el-form-item label="套餐状态" prop="status" style="width: 250px;">
        <el-select
            v-model="queryParams.status"
            placeholder="请选择套餐状态"
            clearable
            @change="handleQuery"
        >
          <el-option
              v-for="dict in sys_job_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="时间范围" style="width: 308px">
        <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['tpackage:tpackage:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['tpackage:tpackage:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tpackage:tpackage:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['tpackage:tpackage:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tpackageList" @selection-change="handleSelectionChange" stripe>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="套餐id" align="center" prop="packId" />
<!--      <el-table-column label="管理员id" align="center" prop="adminId" />-->
      <el-table-column label="套餐名称" align="center" prop="packName" />
      <el-table-column label="套餐价格" align="center" prop="price" >
        <template #default="scope">
          {{ scope.row.price !== null && scope.row.price !== undefined ? scope.row.price.toFixed(2) + ' ￥' : '' }}
        </template>
      </el-table-column>
      <el-table-column label="套餐描述" align="center" prop="description" show-overflow-tooltip>
        <template #default="scope">
          <!--    使用v-html属性，可以渲染字符串是html标签  -->
          <div v-html="scope.row.description"></div>
        </template>
      </el-table-column>
      <el-table-column label="管理员" align="center" prop="adminName" />
      <el-table-column label="上架时间" align="center" prop="shopTime" >
        <template #default="scope">
          {{ scope.row.shopTime }} 天
        </template>
      </el-table-column>
      <el-table-column label="套餐状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_job_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip>
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}' ) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" show-overflow-tooltip>
        <template #default="scope">
          <span v-if="scope.row?.updateTime && scope.row.updateTime.trim() !== ''">
            {{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
          </span>
          <span v-else>
            未更新
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['tpackage:tpackage:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['tpackage:tpackage:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改套餐信息管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="tpackageRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="管理员" prop="adminId">
<!--          <el-input v-model="form.adminId" placeholder="请输入管理员id" />-->
          <el-select
              v-model="form.adminId"
              placeholder="请选择管理员"
              clearable
              filterable
              style="width: 100%"
              :disabled="isEditMode"
          >
            <el-option
                v-for="admin in adminOptions"
                :key="admin.value"
                :label="admin.label"
                :value="admin.value"
                :disabled="admin.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="套餐名称" prop="packName">
          <el-input v-model="form.packName" placeholder="请输入套餐名称" />
        </el-form-item>
        <el-form-item label="套餐价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入套餐价格" />
        </el-form-item>
        <el-form-item label="套餐描述">
          <editor v-model="form.description" :min-height="192"/>
        </el-form-item>
        <el-form-item label="上架时间" prop="shopTime">
          <el-select
              v-model="form.shopTime"
              placeholder="请选择上架时间"
              clearable
          >
            <el-option
                v-for="item in shopTimeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="套餐状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
                v-for="dict in sys_job_status"
                :key="dict.value"
                :value="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Tpackage">
import { listTpackage, getTpackage, delTpackage, addTpackage, updateTpackage } from "@/api/tpackage/tpackage"
import {parseTime} from "../../../utils/ruoyi.js";
import {listAdmin} from "@/api/admin/admin.js";

const { proxy } = getCurrentInstance()
const { sys_job_status} = proxy.useDict("sys_job_status")

const tpackageList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

//日期范围
const dateRange = ref([])
const shopTimeOptions = ref([
  { label: '7天', value: 7 },
  { label: '14天', value: 14 },
  { label: '30天', value: 30 }
])
// 管理员下拉框选项
const adminOptions = ref([]);
// 添加管理员状态映射
const adminStatusMap = ref({})
const isEditMode = ref(false); //是否可编辑

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    packId: null,
    adminId: null,
    packName: null,
    price: null,
    description: null,
    shopTime: null,
    status: null,
    beginTime:null,
    endTime:null,
  },
  rules: {
    adminId: [
      { required: true, message: "管理员不能为空", trigger: "blur" }
    ],
    packName: [
      { required: true, message: "套餐名称不能为空", trigger: "blur" }
    ],
    price: [
      { required: true, message: "套餐价格不能为空", trigger: "blur" }
    ],
    description: [
      { required: true, message: "套餐描述不能为空", trigger: "blur" }
    ],
    shopTime: [
      { required: true, message: "上架时间不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "套餐状态不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

function getAdminList() {
  listAdmin().then(response => {
    // 构建管理员状态映射
    const statusMap = {}
    response.rows.forEach(admin => {
      statusMap[admin.adminId] = admin.status
    })
    adminStatusMap.value = statusMap

    // 构建下拉选项
    adminOptions.value = response.rows.map(admin => ({
      label: admin.status === '1' ? `${admin.username}(停用)` : admin.username,
      value: admin.adminId,
      disabled: admin.status === '1'
    }));
  });
}

/** 查询套餐信息管理列表 */
function getList() {
  loading.value = true
  listTpackage(queryParams.value).then(response => {
    tpackageList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    packId: null,
    adminId: null,
    packName: null,
    price: null,
    description: null,
    shopTime: null,
    status: null,
    /*createTime: null,
    updateTime: null,*/
  }
  proxy.resetForm("tpackageRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  console.log(dateRange.value)
  // 设置日期范围参数
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.beginTime = dateRange.value[0];
    queryParams.value.endTime = `${dateRange.value[1]} 23:59:59`;
  } else {
    queryParams.value.beginTime = null;
    queryParams.value.endTime = null;
  }
  console.log(queryParams.value)
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  // 重置日期参数
  queryParams.value.beginTime = null
  queryParams.value.endTime = null
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.packId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  form.value.status = '0' // 默认正常状态
  getAdminList(); // 加载管理员列表
  isEditMode.value = false; // 新增模式不禁用
  open.value = true
  title.value = "添加套餐信息管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _packId = row.packId || ids.value
  getTpackage(_packId).then(response => {
    form.value = response.data
    getAdminList(); // 加载管理员列表
    isEditMode.value = true; // 更新模式禁用
    open.value = true
    title.value = "修改套餐信息管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["tpackageRef"].validate(valid => {
    if (valid) {
      if (form.value.packId != null) {
        updateTpackage(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addTpackage(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _packIds = row.packId || ids.value
  proxy.$modal.confirm('是否确认删除套餐信息管理编号为"' + _packIds + '"的数据项？').then(function() {
    return delTpackage(_packIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('tpackage/tpackage/export', {
    ...queryParams.value
  }, `tpackage_${new Date().getTime()}.xlsx`)
}

getList()
</script>
